'use strict';

angular.module('com.dcos.app').controller('EditPasswordController', function EditPasswordController($uibModalInstance, $q, $cookies, dialog, LoginService,PrivilegeService) {
  var vm = this;
  var token = $cookies.getObject('token');
  vm.name = token.user.name;
  vm.userId = token.user.id;

  vm.submitted = false;
  vm.submit = function(myForm){
  	vm.submitted = true;
  	if(myForm.$invalid){
  		return;
  	}

    LoginService.editPassword(vm.userId, vm.oldPassword, vm.newPassword).then(function(response){
      PrivilegeService.getAllHarbors().then(function(response){
        vm.allHarbors=response.data || [];
        var promiseArr = [];
        for(var i=0,len=vm.allHarbors.length; i<len; i++){
          var data = {
            "user":vm.name,
            "url":vm.allHarbors[i].url,
            "old_password":vm.oldPassword,
            "new_password":vm.newPassword
          };
          promiseArr.push(LoginService.modifyPwd(data));
        }
        return $q.all(promiseArr);
      }).then(function () {
        $uibModalInstance.close();
        dialog.alert('用户密码修改成功！');
      }).catch(function (e) {
        if (e.status == 401) return;
        dialog.alert('用户登录密码修改成功，对应镜像仓库密码修改失败！');
      });
    }).catch(function(e){
      if(e.status == 401){
        dialog.alert("原始密码输入错误或会话已过期！");
      }else{
        dialog.alert('修改密码失败！');
      }
    });
  }

  vm.cancel = function(){
  	$uibModalInstance.dismiss('cancel');
  }
});
